﻿using GalaSoft.MvvmLight.Messaging;
using KINLO.DRV.Drv;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KINLO.DRV.Machine
{
   public  class ElecBalanceMachine
    {
        #region 字段
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ElecBalanceMachine));
        HTNElectronicBalanceSocketDrv ElecBalance;
        System.Timers.Timer timer;
        public string ID { get; set; }
        public bool IsWeightFin { get; set; }
        public bool IsST { get; set; }
        public Decimal Weight { get; set; }
        public string CurWeight { get; set; }
        public string Unit { get; set; }
        #endregion

        #region 方法
        public ElecBalanceMachine(string ip, int port, string id, double interval = 300, int dataLen = 20)
        {
            ID = id;
            this.IP = ip;
            this.Port = port;
            ElecBalance = new HTNElectronicBalanceSocketDrv(ip, port, dataLen);
            timer = new System.Timers.Timer(interval);
            timer.Elapsed += Timer_Elapsed;
           // Messenger.Default.Register<bool>(this, "ElecBalance", LoopRead);
        }
        static int inTimer = 0;
        string IP;
        int Port;
        object locker = new object();
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if(Monitor.TryEnter(locker))
            {
                try
                {
                    HandleMessage1(Read());

                }
                finally
                {
                    Monitor.Exit(locker);
                }
            }
            //try
            //{
            //    if (Interlocked.Exchange(ref inTimer, 1) == 0)
            //    {
            //        HandleMessage1(Read());
            //    }
            //}
            //finally
            //{
            //    Interlocked.Exchange(ref inTimer, 0);
            //}
        }
        public bool IsLoop = true;
        public void LoopRead()
        {
            log.Info("LoopRead1");
            while (IsLoop)
            {
                if (ElecBalance.Connected != true)
                {
                    ElecBalance.Open();
                }
                else
                {
                    log.Info("LoopRead3");
                    HandleMessage(Read());
                }
                Interlocked.Exchange(ref inTimer, 0);
            }
            IsLoop = true;

        }

        void HandleMessage1(byte[] msg)
        {
            if (msg != null&&msg.Length==20)
            {
                var sect = Encoding.Default.GetString(msg);
                var section1 = Encoding.Default.GetString(msg, 0, 2);
                //var section2 = Encoding.Default.GetString(msg, 3, 2);
                //var section3 = Encoding.Default.GetString(msg, 6, 1);
                var section4 = Encoding.Default.GetString(msg, 7, 7);
                var section5 = Encoding.Default.GetString(msg, 14, 4);
                //log.Info(string.Format("称重结果:{0} {1} {2} {3} {4}", section1, section2, section3, section4, section5));

                CurWeight = section4;
                if (section1.ToUpper() == "ST")
                {
                    var w = Decimal.Parse(section4);
                    if (w < 10)
                        return;
                    Weight = w;
                    Unit = section5;
                    IsWeightFin = true;
                    IsST = true;
                   // ServiceControl(false); 
                }
            }
        }
        void HandleMessage(byte[] msg)
        {
            if(msg!=null)
            {
                var sect = Encoding.Default.GetString(msg);
                var section1 = Encoding.Default.GetString(msg, 0, 2);
                var section2 = Encoding.Default.GetString(msg, 3, 2);
                var section3 = Encoding.Default.GetString(msg, 6, 1);
                var section4 = Encoding.Default.GetString(msg, 7, 7);
                var section5 = Encoding.Default.GetString(msg, 15, 2);
                log.Info(string.Format("称重结果:{0} {1} {2} {3} {4}", section1, section2, section3, section4, section5)); 
                if (section1.ToUpper() == "ST")
                {
                    var w= Decimal.Parse(section4);
                    if (w < 1)
                        return;
                    Weight = w;
                    Unit = section5;
                    IsWeightFin = true;
                    IsLoop = false;
                    //ServiceControl(false);
                    ElecBalance.Disconnect();
                }
            }
        }
        public bool Connected
        {
            get { return ElecBalance.Connected; }
        }
        public byte[] Read()
        {
            return ElecBalance.Read();
        }
        /// <summary>
        /// 1启动称重 0 停止称重
        /// </summary>
        /// <param name="act"></param>
        public void ServiceControl(bool act)
        {
            if (act == false)
            {
                ElecBalance.Disconnect();
            }
            if (act == true && ElecBalance.Connected != true)
            {
                ElecBalance.Open();
            }
            timer.Enabled = act;
        }
        public void ClearZero()
        {

            ElecBalance.ClearZero();
            log.Info(string.Format("电子称清零完成"));
        }
        #endregion
    } 
}
